#!/bin/bash

# 解析参数
while [[ $# -gt 0 ]]; do
    case "$1" in
        -t|--type)
            TYPE=$2
            shift 2
            ;;
        -n|--name)
            NAME=$2
            shift 2
            ;;
        -s|--timer-spec)
            TIMER_SPEC=$2
            shift 2
            ;;
        *)
            echo "Unknown option: $1"
            exit 1
            ;;
    esac
done

# 检查参数是否齐全
if [[ -z "$TYPE" || -z "$NAME" ]]; then
    echo "Usage: $0 --type <auto|manual|timer> --name <service-name> [--timer-spec <timer-spec>]"
    exit 1
fi

# 如果是timer类型，检查是否提供了timer-spec
if [[ "$TYPE" == "timer" && -z "$TIMER_SPEC" ]]; then
    echo "Error: Timer type requires --timer-spec to specify the timer schedule."
    exit 1
fi

# 定义脚本目录和路径
SCRIPT_DIR="/usr/local/bin/service"
SCRIPT_FILE="$SCRIPT_DIR/${NAME}.sh"

# 检查目录是否存在，如果不存在则创建
if [ ! -d "$SCRIPT_DIR" ]; then
    mkdir -p "$SCRIPT_DIR"
    echo "目录 $SCRIPT_DIR 已创建。"
fi

# 创建脚本文件并添加#!/bin/bash
echo "#!/bin/bash" > "$SCRIPT_FILE"
chmod +x "$SCRIPT_FILE"

# 创建service文件
SERVICE_FILE="/etc/systemd/system/${NAME}.service"
cat <<EOF > "$SERVICE_FILE"
[Unit]
Description=${NAME} Service
After=network.target

[Service]
ExecStart=${SCRIPT_FILE}
Restart=on-failure
RestartSec=5s

[Install]
WantedBy=multi-user.target
EOF

# 重新加载systemd配置
systemctl daemon-reload

# 根据类型处理
case "$TYPE" in
    auto)
        systemctl enable "$NAME"
        systemctl start "$NAME"
        ;;
    manual)
        echo "Service '$NAME' created. You can start it manually with 'systemctl start $NAME'."
        ;;
    timer)
        TIMER_FILE="/etc/systemd/system/${NAME}.timer"
        cat <<EOF > "$TIMER_FILE"
[Unit]
Description=${NAME} Timer

[Timer]
OnCalendar=${TIMER_SPEC}
Persistent=true

[Install]
WantedBy=timers.target
EOF
        systemctl enable "$NAME.timer"
        systemctl start "$NAME.timer"
        ;;
    *)
        echo "Invalid type: $TYPE. Use 'auto', 'manual', or 'timer'."
        exit 1
        ;;
esac

echo "Service '$NAME' created successfully."
echo "Script '$SCRIPT_FILE' created successfully."